﻿using RStudio.UIFramwork.Pool;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using UnityEngine;


namespace RStudio.UIFramwork
{
    /// <summary>
    /// 管理场景内在活跃UI实例
    /// </summary>
    public class UIModuleAlive
    {
        public UIModuleAlive()
        {
            this.ActiveUIDic = new Dictionary<Type, List<UIBase>>();
            this.CurrentActives = new List<UIBase>();

            this.HandlerActive = BindActive();
            this.HandlerDeActive = BindDeActive();
        }



        [Description("活跃列表")] public Dictionary<Type, List<UIBase>> ActiveUIDic { get; private set; }
        [Description("处理器链")] public IUIHandler HandlerActive { get; private set; }
        [Description("处理器链")] public IUIHandler HandlerDeActive { get; private set; }



        #region 实例管理机制

        /// <summary>
        /// 添加UI实例
        /// </summary>
        /// <remarks>
        /// <see cref="UIBase.ActiveUI()"/> 在 <see cref="HandlerUIActive"/> 中实现。
        /// </remarks>
        public void Append(Type type)
        {
            this.PrepareDic(type);

            #region 实例注册

            var cacheList = this.ActiveUIDic[type];

            UIBase uiBase;
            if (cacheList.Count == 0)
            {
                GameObject prefab = UnitPoolCenter.Get(type).Get();
                uiBase = prefab.GetComponent<UIBase>();
                cacheList.Add(uiBase);
            }
            else
            {
                uiBase = cacheList.First();
            }
        
            this.HandlerActive.Handle(uiBase);
            #endregion
        }

        /// <summary>
        /// 移除指定类型的UI实例
        /// </summary>
        /// <remarks>
        /// 该方法忽略 <see cref="UIBase.CanBeClosed"/> 条件直接移除类型
        /// </remarks>
        public void Remove(Type type)
        {
            if (type == null) return;
            bool isGet = ActiveUIDic.TryGetValue(type, out _);
            if (!isGet)
            {
                Debug.LogWarning($"类型 {type.Name} 没有活跃的UI实例，无需关闭");
                return;
            }


            foreach (var ui in ActiveUIDic[type])
            {
                this.DoDispose(ui);
            }

            ActiveUIDic.Remove(type);
        }

        /// <summary>
        /// 移除指定的UI实例
        /// </summary>
        public void Remove(UIBase uiBase)
        {
            if (uiBase == null) return;

            Type type = uiBase.GetType();
            if (ActiveUIDic.TryGetValue(type, out var uiList) && uiList.Remove(uiBase))
            {
                // 执行生命周期
                // 清理标识
                // 回收实例
                this.DoDispose(uiBase);


                if (uiList.Count == 0)
                {
                    ActiveUIDic.Remove(type);
                }
            }
        }

        /// <summary>
        /// 回收机制
        /// </summary>
        /// <param name="uiBase"></param>
        /// <remarks>
        /// 含 <see cref="UIBase.DeActiveUI()"/>
        /// </remarks>
        public void DoDispose(UIBase uiBase)
        {
            this.HandlerDeActive.Handle(uiBase);
            this.CurrentActives.Remove(uiBase);

            UnitPoolCenter.Get(uiBase.GetType()).Recycle(uiBase.gameObject);
        }

        #endregion



        /// <summary>
        /// 准备活跃存储池
        /// </summary>
        private void PrepareDic(Type type)
        {
            bool isGet = this.ActiveUIDic.TryGetValue(type, out _);
            if (!isGet)
            {
                List<UIBase> output = new();
                ActiveUIDic.TryAdd(type, output);
            }
        }

        #region 处理器逻辑
        /// <summary>
        /// 装饰处理器
        /// </summary>
        private IUIHandler BindActive()
        {
            var _UIHandlers = new IUIHandler[] {
                new HandlerUseClosePre(this),
                new HandlerUseAsSingle(),
                new HandlerUseMask(),
                new HandlerUseBlock(),
                new HandlerUseAreaQuit(),
                new HandlerResetTransform(),
                new HandlerUseRecord(),
                new HandlerResetSibling(),
                new HandlerManageActives(this, true),
                new HandlerUIActive(),
            };

            for (int i = 0; i < _UIHandlers.Length - 1; i++)
            {
                _UIHandlers[i].Next = _UIHandlers[i + 1];
            }

            return _UIHandlers[0];
        }

        /// <summary>
        /// 装饰处理器
        /// </summary>
        private IUIHandler BindDeActive()
        {
            var _UIHandlers = new IUIHandler[] {
                new HandlerUseMask(false),
                new HandlerUseBlock(false),
                new HandlerUseAreaQuit(false),
                new HandlerManageActives(this, false),
                new HandlerUIDeActive(),
            };

            for (int i = 0; i < _UIHandlers.Length - 1; i++)
            {
                _UIHandlers[i].Next = _UIHandlers[i + 1];
            }

            return _UIHandlers[0];
        }
        #endregion 

        #region 活跃管理机制
        [Description("当前最新活跃")] public List<UIBase> CurrentActives { get; private set; }

        public bool TryRemove(UIEventArgs uiEvent)
        {
            if (uiEvent.UIEventType != UIEventType.Back) return false;

            if (uiEvent.Type == GetNew().GetType())
            {
                Remove(uiEvent.UIBase);
                return true;
            }


            return false;
        }

        /// <summary>
        /// 获取最新位置
        /// </summary>
        /// <returns></returns>
        private UIBase GetNew()
        {
            if (this.CurrentActives.Count == 0)
                return null;

            return this.CurrentActives[^1];
        }
        public void AddActive(UIBase uiBase)
        {
            this.CurrentActives.Add(uiBase);
        }
        public void RemoveActive(UIBase uiBase)
        {
            this.CurrentActives.Remove(uiBase);
        }
        #endregion
    }
}